/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eightbears.beboy.ui.chat.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.GroupCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.entity.ChatGroupEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.Adapter.GroupAdapter;
import com.eightbears.greendao.GroupList;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.exceptions.HyphenateException;

import java.util.List;

import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_GROUP_LIST;

public class GroupsActivity extends BaseActivity {


    public static final String TAG = "GroupsActivity";
    private ListView groupListView;
    protected List<EMGroup> grouplist;
    private GroupAdapter groupAdapter;
    private InputMethodManager inputMethodManager;
    public static GroupsActivity instance;
    private View progressBar;
    private SwipeRefreshLayout swipeRefreshLayout;

    private String groupId;

    private List<GroupList> groups;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            swipeRefreshLayout.setRefreshing(false);
            switch (msg.what) {
                case 0:
                    refresh();
                    break;
                case 1:
                    Toast.makeText(GroupsActivity.this, R.string.Failed_to_get_group_chat_information, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.eightbears.beboy.R.layout.em_fragment_groups);
        groups = GroupCache.getInstance(GroupsActivity.this).getAllData();
        instance = this;
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        grouplist = EMClient.getInstance().groupManager().getAllGroups();
        groupListView = (ListView) findViewById(R.id.list);
        if(null != groups) {
            for (int i = 0; i < groups.size(); i++) {
                EMGroup group = EMClient.getInstance().groupManager().getGroup(groups.get(i).getGroupid());
                if (null == group) {
                    GroupCache.getInstance(getApplication()).deleteGroupByID(groups.get(i).getGroupid());
                    groups.remove(i);
                }
            }

            //show group list
            groupAdapter = new GroupAdapter(this, 1, groups);
            groupListView.setAdapter(groupAdapter);
        }

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
        swipeRefreshLayout.setColorSchemeResources(
                R.color.text_select_color,
                R.color.text_select_color,
                R.color.text_select_color,
                R.color.text_select_color);
        //pull down to refresh
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            EMClient.getInstance().groupManager().getJoinedGroupsFromServer();
                            handler.sendEmptyMessage(0);
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                            handler.sendEmptyMessage(1);
                        }
                    }
                }.start();
            }
        });

        groupListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                groupId = groupAdapter.getItem(position - 1).getGroupid();
                start2Chat();
            }
        });
        groupListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                    if (getCurrentFocus() != null)
                        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });
        SwipeBackLayout swipeBackLayout = (SwipeBackLayout) findViewById(R.id.sw_finish);
        swipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    private void start2Chat() {
        Intent intent = new Intent(GroupsActivity.this, ChatActivity.class);
        intent.putExtra("chatType", CommonAPI.CHATTYPE_GROUP);
        intent.putExtra("userId", groupId);
        startActivityForResult(intent, 0);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        refresh();
        super.onResume();
    }

    private void refresh() {
        getGroupList();
    }

    /**
     * 获取所有群
     */
    private void getGroupList() {
        OkHttpUtils.get().url(URL_GROUP_LIST)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                if(response.contains(",\"data\":[]")){
                    return;
                }
                ChatGroupEntity groupEntity = GsonUtil.fromJson(response, ChatGroupEntity.class);
                if(response.contains(CONNECTION_STATUS_SUCCESS) && null != groupEntity){
                    if (null == groupEntity.getData())
                        return;
                    GroupCache.getInstance(GroupsActivity.this).insertAll(groupEntity.getData().getList());
                    groups = GroupCache.getInstance(GroupsActivity.this).getAllData();
                    groupAdapter = new GroupAdapter(GroupsActivity.this, 1, groups);
                    groupListView.setAdapter(groupAdapter);
                    groupAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(GroupsActivity.this, status_error);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    public void back(View view) {
        finish();
    }





    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {

    }
}
